import axios from "axios";
import type { AxiosRequestConfig, AxiosResponse } from "axios";
import type { ResponseResult } from "@/entity/ResponseResult";
import { useAuthStore } from "@/stores/auth";

/**
 * 与后端约定鉴权请求头
 */
export const AUTH_HEADER_KEY = "Authorization";
export const TOKEN_HEAD = "Bearer ";

/**
 * Http请求工具类，封装axios
 */
export class HttpClient {
    getAxios() {
        return axios;
    }

    get(url: string, needAuth?: boolean, config?: AxiosRequestConfig<any>): Promise<AxiosResponse<ResponseResult<any>, any>> {
        return axios.get(url, this.appendAuthHeader(needAuth, config));
    }

    post(url: string, data?: any, needAuth?: boolean, config?: AxiosRequestConfig<any>): Promise<AxiosResponse<ResponseResult<any>, any>> {
        return axios.post(url, data, this.appendAuthHeader(needAuth, config));
    }

    put(url: string, data?: any, needAuth?: boolean, config?: AxiosRequestConfig<any>): Promise<AxiosResponse<ResponseResult<any>, any>> {
        return axios.put(url, data, this.appendAuthHeader(needAuth, config));
    }

    patch(url: string, data?: any, needAuth?: boolean, config?: AxiosRequestConfig<any>): Promise<AxiosResponse<ResponseResult<any>, any>> {
        return axios.patch(url, data, this.appendAuthHeader(needAuth, config));
    }

    delete(url: string, needAuth?: boolean, config?: AxiosRequestConfig<any>): Promise<AxiosResponse<ResponseResult<any>, any>> {
        return axios.delete(url, this.appendAuthHeader(needAuth, config));
    }

    request(config: AxiosRequestConfig<any>): Promise<AxiosResponse<ResponseResult<any>, any>> {
        return axios.request(config);
    }

    /**
     * 添加鉴权请求头
     * @param needAuth 是否需要鉴权，默认为true
     * @param config 
     * @returns 
     */
    appendAuthHeader(needAuth: boolean = true, config?: AxiosRequestConfig<any>) {
        if (!needAuth) {
            return config;
        }
        if (!config) {
            config = {
                headers: {}
            };
        } else if (config && !config.headers) {
            config.headers = {};
        }

        const authStore = useAuthStore();
        if (config && config.headers && !config.headers[AUTH_HEADER_KEY]) {
            config.headers[AUTH_HEADER_KEY] = TOKEN_HEAD + authStore.token;
        }

        return config;
    }
}

export const httpClient = new HttpClient();

export default httpClient;